/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package cn.lang.auth.oauth2;

import cn.lang.auth.common.manager.CacheManager;
import cn.lang.auth.common.utils.jwt.JwtUtil;
import cn.lang.auth.pojo.dto.SysUserDto;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
* @title: OAuth2Realm
* @description: 认证
* @author: Lang 1102076808@qq.com
* @date: 2020/6/18 23:32
*/
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // <1> 获得 SysUserDto 对象
        Long userId = Long.valueOf(String.valueOf(principals.getPrimaryPrincipal())) ;
        SysUserDto user = CacheManager.getUser(userId);
        // <2> 用户权限列表
        Set<String> permsSet = user.getPerms();
        // <3> 创建 SimpleAuthorizationInfo 对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();
        if(!JwtUtil.verifyToken(accessToken)){
            throw new RuntimeException("身份认证失败，请重新登录");
        }
        //token失效
        if(JwtUtil.isExpired(accessToken)){
            throw new RuntimeException("登录失效，请重新登录");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(JwtUtil.getUid(accessToken), accessToken, getName());
        return info;
    }
}
